from django.http import JsonResponse
from rest_framework.views import APIView
from .models import Param
from .serializers import ListSerializer
from .validate import AddValidate, EditValidate
from utils.utils import responseSuccess, responseError, validateError, serializerJSON, filterFields, MyPaginator

# 列表数据
class ListAPI(APIView):
    def get(self,req):
        queryDict = req.query_params.dict()
        filterDict = filterFields(Param, queryDict)
        objs = Param.objects.filter(**filterDict)
        paginator = MyPaginator(objs, **queryDict)
        serializers = ListSerializer(paginator.object_list, many=True)
        datas = serializerJSON(serializers)
        data = paginator.data(datas)
        return JsonResponse(responseSuccess(data), safe=False)

# 新增/修改
class SubmitAPI(APIView):
    # 新增
    def post(self,req):
        data = req.data
        edit_id = data.get('id')
        if edit_id:
            obj = Param.objects.get(id=int(edit_id))
            form = EditValidate(obj, data=data)
        else:
            form = AddValidate(data=data)
        if form.is_valid():
            if edit_id:
                obj = form.update(obj, form.validated_data)
            else:
                obj = form.create(form.validated_data)
            return JsonResponse(responseSuccess(str(obj.pk)), safe=False)
        # 格式化错误信息
        arr = validateError(form.errors)
        return JsonResponse(responseError(arr), safe=False)

# 删除
class RemoveAPI(APIView):
    def post(self,req):
        ids = req.query_params.dict().get('ids')
        if not ids:
            return JsonResponse(responseError('ids不能为空'), safe=False)
        ids = ids.split(',')
        if not Param.objects.filter(id__in=ids).exists():
            return JsonResponse(responseError('删除对象不存在'), safe=False)
        result = Param.objects.filter(id__in=ids).delete()
        if result:
            return JsonResponse(responseSuccess(), safe=False)
        return JsonResponse(responseError('删除失败'), safe=False)